<?php
/**
 * created by zzy
 * date: 2018/1/26 14:07
 */


namespace App\Api\Service\Seller\Controllers;


use App\Eloquent\Area;
use App\Eloquent\City;
use App\Eloquent\Province;
use App\Eloquent\Ygt\DepartmentUser;
use App\Eloquent\Ygt\ImgUpload;
use App\Eloquent\Ygt\Seller;
use App\Eloquent\Ygt\SellerCompany;
use App\Eloquent\Ygt\SellerRelation;
use App\Eloquent\Ygt\User;
use App\Engine\Func;
use Framework\BaseClass\Api\Controller;

class IndexController extends Controller
{
    public $userId        = 25;
    public function index(){}
    public function lists()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $title              = request('keyword','');
        $level              = request('seller_level',0);
        $materialId              = request('material_id',0);
        if( !$userInfo ){
            xThrow( ERR_PARAMETER );
        }
        $companyId          = $userInfo->company_id;
        $where              = ['company_id'=>$companyId];
        if($title)
        {
            $where['title'] = ['like','%'.$title.'%'];
        }

        //level == 999 时不是筛选等级，只是不限制主营材料
        if( ($level>0) && ($level != 999))
        {
            $where['level'] = $level;
        }

        //如果设置了显示所有供应商，不再筛选主营业务
        if($materialId){
            //过滤已经有材料勾选的供应商ID -- 取消过滤
//            $sellerCompanyIdExistArr = \App\Eloquent\Ygt\Product::where(['assemblage_material_id'=>$materialId])->get()->pluck('seller_company_id')->toArray();
            $sellerCompanyIdExistArr = [];
            if($level == 999){//显示所有供应商
                $where['id']   = ['notIn',$sellerCompanyIdExistArr];
            }else{
                //筛选有主营业务的供应商列表
                $sellerCompanyIdArr = \App\Eloquent\Ygt\SellerCompanyMaterial::where(['assemblage_material_id'=>$materialId])->get()->pluck('seller_company_id')->toArray();
                foreach ($sellerCompanyIdArr as $tmpKey => $tmpValue){
                    if(in_array($tmpValue,$sellerCompanyIdExistArr)){
                        unset($sellerCompanyIdArr[$tmpKey]);
                    }
                }
                $where['id']   = ['in',$sellerCompanyIdArr];
            }
        }


        $collection         = SellerCompany::getList($where);
        $levelArr           = SellerCompany::getLevelListByType(2);
        $imgIdArr           = [];
        foreach($collection as $key=>$val)
        {
            $imgIdArr[]     = $val->img_id;
            $collection[$key]->address_address  = $val->province_name.$val->city_name.$val->area_name.$val->address;

            $valLevel       = $val->level;
            $levelName      = isset($levelArr[$valLevel]) ? $levelArr[$valLevel] : '';
            $collection[$key]->level_name       = $levelName;

            $collection[$key]->img_path          = '';
            $collection[$key]->total_money      = '';
            $collection[$key]->pay_money        = '';

            ////获取最近一次采购单价&总额
            $lastPruchasePrice = '';
            $tmpSupplierId = $val->id;
            //获取最近采购单
            $tmpPurchaseRow = \App\Eloquent\Ygt\Purchase::where(['supplier_id'=>$tmpSupplierId])->orderBy('created_at','desc')->first();
            if($tmpPurchaseRow){
                $tmpPurchaseMaterilList = \App\Eloquent\Ygt\PurchaseMaterial::where(['purchase_id'=>$tmpPurchaseRow['id']])->get();
                $tmpMoneyAll = 0;
                $tmpNumber = 0;
                foreach ($tmpPurchaseMaterilList as $tmpPurchaseMaterilRow){
                    $tmpMoneyAll += $tmpPurchaseMaterilRow['price']*$tmpPurchaseMaterilRow['num'];
                    $tmpNumber += $tmpPurchaseMaterilRow['num'];
                }

                $averagePrice = 0;
                if($tmpNumber){
                    $averagePrice = $tmpMoneyAll / $tmpNumber;
                }

                $tmpMoneyAll = sprintf('%.2f',$tmpMoneyAll);
                $averagePrice = sprintf('%.2f',$averagePrice);


                $lastPruchasePrice = '最近采购单价¥'.$averagePrice.",总价¥".$tmpMoneyAll;
            }
            $collection[$key]->last_pruchase_price        = $lastPruchasePrice;

            //供应商主营材料名称
            //改为材料分类 zhuyujun 20181116
//            $materialIds = $val->main_product;
//            $materialIdArr = explode(',',$materialIds);
//            $materialNameArr = \App\Eloquent\Ygt\AssemblageMaterial::whereIn('id',$materialIdArr)->get()->pluck('product_name')->toArray();
//            $materialNames = '';
//            if(!empty($materialNameArr)){
//                $materialNames = implode(',',$materialNameArr);
//            }

            $materialNames = '';
            $categoryIdStr = $val->main_product;
            if ($categoryIdStr) {
                $categoryIdArr = explode(',', $categoryIdStr);

                //获取分类名称
                $materialNames = \App\Eloquent\Ygt\Category::whereIn('id',$categoryIdArr)->get()->pluck('cat_name')->toArray();
                if(!empty($materialNames)){
                    $materialNames = implode(',',$materialNames);
                }else{
                    $materialNames = '';
                }
            }

            $collection[$key]->main_product_str = $materialNames;

        }
        if($imgIdArr)
        {
            $where          = ['id'=>['in',$imgIdArr]];
            $fields         = 'id,img_url';
            $imgPathList    = ImgUpload::getList($where,$fields);
            $imgPathArr     = [];
            foreach($imgPathList as $key=>$val)
            {
                $valId      = $val['id'];
                $valImgUrl  = $val['img_url'];
                $imgPath    = Func::getImgUrlHttp($valImgUrl);
                $imgPathArr[$valId]     = $imgPath;
            }
            foreach($collection as $key=>$val)
            {
                $imgId                       = $val->img_id;
                $imgPath                     = isset($imgPathArr[$imgId]) ? $imgPathArr[$imgId] : '';
                $collection[$key]->img_path = $imgPath;
            }
        }
        $lists              = Func::getLetterList($collection);
//        $letterArr          = $collection->pluck('first_letter')->all();
//        $lists              = [];
//        if($letterArr)
//        {
//            $letterArr      = array_unique($letterArr);
//            sort($letterArr);
//            $listArr            = $collection->groupBy('first_letter')->toArray();
//            foreach($letterArr as $key=>$val)
//            {
//                $lists[$key]['letter']      = $val;
//                $lists[$key]['list']       = $listArr[$val];
//            }
//        }
        return $lists;
    }
    public function edit()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        if( !$userInfo )
        {
            xThrow( ERR_PARAMETER,'登录超时' );
        }
        $companyId              = $userInfo->company_id;
        $id                     = request('id',0);//有值时编辑,无值是添加
        $isEdit                 = $id == 0 ? 0 : 1;
        if($isEdit == 0){
            //添加供应商
            $contactMobile      = request('contact_mobile',0);
            $title              = request('title',0);
            if(!$contactMobile)
            {
                xThrow( ERR_PARAMETER);
            }
            //判断供应商是否存在
            $registerResult     = User::registerByType($contactMobile,$title,2);
            $registerStatus     = $registerResult['status'];
            $registerUserId     = $registerResult['user_id'];
            $registerMessage    = $registerResult['message'];
            //$registerStatus 0失败,1不存在插入成功,2已存在取值成功
            if($registerStatus == 1){
                //若是新注册的则需插入的员工表,,注意这时的厂id是特殊的
                $sellerArr              = config('ygt.seller_arr');
                $registerCompanyId      = $sellerArr['company_id'];
                $privilegeId            = $sellerArr['privilege_id'];
                $departmentUserData     = [
                    'user_id'=>$registerUserId,
                    'company_id'=>$registerCompanyId,
                    'privilege_id'=>$privilegeId,
                    'mobile'=>$contactMobile,
                    'truename'=>$title,
                ];
                DepartmentUser::insertOneData( $departmentUserData );
            }else if($registerStatus == 2){
                //暂时不需要做处理
            }else{
                xThrow(ERR_PARAMETER, $registerMessage);
            }
            $sellerUserId           = $registerUserId;
            $resultMessageArr       = ['success'=>'添加成功','error'=>'添加失败'];
        }else{
            //编辑供应商
            $where          = ['id'=>$id];
            $info           = SellerCompany::getInfo($where);
            if(!$info)
            {
                xThrow(ERR_UNKNOWN,'该信息不存在');
            }
            $sellerUserId       = $info->user_id;
            $resultMessageArr   = ['success'=>'编辑成功','error'=>'编辑失败'];
        }
        $data               = request()->all();
        //省市县
        $provinceName       = $cityName = $areaName = '';
        if(isset($data['province_id']))
        {
            $provinceId     = $data['province_id'];
            $where          = ['provinceID'=>$provinceId];
            $collection     = Province::where($where)->first();
            if($collection)
            {
                $provinceName   = $collection->province;
            }
        }
        if(isset($data['city_id']))
        {
            $cityId         = $data['city_id'];
            $where          = ['cityID'=>$cityId];
            $collection     = City::where($where)->first();
            if($collection)
            {
                $cityName       = $collection->city;
            }
        }
        if(isset($data['area_id']))
        {
            $areaId         = $data['area_id'];
            $where          = ['areaID'=>$areaId];
            $collection     = Area::where($where)->first();
            if($collection)
            {
                $areaName       = $collection->area;
            }
        }
        $data['province_name']  = $provinceName;
        $data['city_name']      = $cityName;
        $data['area_name']      = $areaName;
        //首字母
        $firstLetter        = '#';
        if(isset($data['title']))
        {
            $title              = $data['title'];
            $pinyin             = app('pinyin')->abbr($title);
            $firstLetter        = strtoupper(substr($pinyin,0,1));
            $letterAll          = [];
            for($i=65;$i<91;$i++){
                $letterAll[]    = chr($i);
            }
            if(!in_Array($firstLetter,$letterAll))
            {
                $firstLetter    = '#';
            }
        }
        $data['first_letter']   = $firstLetter;
        //其它信息
        $data['company_id']     = $companyId;
        $data['user_id']        = $sellerUserId;

        $fieldList              = SellerCompany::$tableFieldList;
        $tableData              = SellerCompany::setDataByTableField($data,$fieldList);
        $tableDataCheckResult   = SellerCompany::checkDataByTableField($tableData,$fieldList);
        if($tableDataCheckResult !== true)
        {
            xThrow(ERR_PARAMETER, $tableDataCheckResult);
        }
        $relationId             = SellerCompany::editData($tableData,'id');




        if($relationId===false)
        {
            xThrow(ERR_UNKNOWN,$resultMessageArr['error']);
        }else{
            if($id){
                $sellerCompanyId = $id;
            }else{
                $sellerCompanyId = $relationId;
            }

            //添加供应商和主营材料的关系
//            $materialIds  = request('main_product');
//            $materialIdArr = explode(',',$materialIds);
//            foreach ($materialIdArr as $materialId){
//                $tmpObj = \App\Eloquent\Ygt\SellerCompanyMaterial::firstOrNew(['seller_company_id'=>$sellerCompanyId,'assemblage_material_id'=>$materialId]);
//                $tmpObj->seller_company_id = $sellerCompanyId;
//                $tmpObj->assemblage_material_id = $materialId;
//                $tmpObj->save();
//            }
            //调整为材料分类 zhuyujun 20181116
            $categoryIdStr  = request('main_product');
            if ($categoryIdStr)
            {
                $categoryIdArr      = explode(',', $categoryIdStr);
                foreach($categoryIdArr as $v)
                {
                    if(!$v){//过滤空
                        continue;
                    }

                    $categoryModel = new \App\Eloquent\Ygt\Category();
                    $categoryArr    = $categoryModel->getCategoryOption($v,$companyId);
                    $category       = collect($categoryArr);
                    $tempCategoryIds = $category->map(function ($c) {
                        return $c['id'];
                    })->toArray();
                    $categoryIdArr  = array_merge($categoryIdArr,$tempCategoryIds);
                }

                $categoryIdArr      = array_unique($categoryIdArr);

                //获取集合材料ID列表
                $materialIdArr = \App\Eloquent\Ygt\AssemblageMaterial::whereIn('category_id',$categoryIdArr)->get()->pluck('id');

                foreach ($materialIdArr as $materialId){
                    $tmpObj = \App\Eloquent\Ygt\SellerCompanyMaterial::firstOrNew(['seller_company_id'=>$sellerCompanyId,'assemblage_material_id'=>$materialId]);
                    $tmpObj->seller_company_id = $sellerCompanyId;
                    $tmpObj->assemblage_material_id = $materialId;
                    $tmpObj->save();
                }

                //删除未选择分类下的材料绑定关系
                \App\Eloquent\Ygt\SellerCompanyMaterial::where(['seller_company_id'=>$sellerCompanyId])->whereNotIn('assemblage_material_id',$materialIdArr)->delete();
            }

        }



        return ['message'=>$resultMessageArr['success']];
    }

    public function detail()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $id                 = request('id');
        if(!$userInfo || !$id)
        {
            xThrow(ERR_PARAMETER );
        }
        $companyId          = $userInfo->company_id;
        $where              = ['id'=>$id,'company_id'=>$companyId];
        $info               = SellerCompany::getInfo($where);
        if(!$info)
        {
            xThrow(ERR_UNKNOWN,'该供应商不存在或已被删除' );
        }
        $data               = $info->toArray();
        $data['address_address']= $data['province_name'].$data['city_name'].$data['area_name'].$data['address'];
        $data['img_path']  = Func::getImgUrlById($data['img_id']);
        $levelList          = SellerCompany::getLevelListByType(2);
        $levelName          = isset($levelList[$data['level']]) ? $levelList[$data['level']] : '';
        $data['level_name']  = $levelName;

        //主营产品信息
//        $tmpSellerCompanyMaterialList = \App\Eloquent\Ygt\SellerCompanyMaterial::leftJoin('ygt_assemblage_material','ygt_seller_company_material.assemblage_material_id','=','ygt_assemblage_material.id')
//            ->where(['seller_company_id'=>$id])->select(['ygt_seller_company_material.*','ygt_assemblage_material.product_name'])->get();
//        $mainProduct = $mainProductStr = '';
//        foreach ($tmpSellerCompanyMaterialList as $tmpSellerCompanyMaterialRow){
//            $mainProduct .= $tmpSellerCompanyMaterialRow['assemblage_material_id'].',';
//            $mainProductStr .= $tmpSellerCompanyMaterialRow['product_name'].',';
//        }
//
//        if($mainProduct){
//            $mainProduct = substr($mainProduct, 0, -1);
//        }
//        if($mainProductStr){
//            $mainProductStr = substr($mainProductStr, 0, -1);
//        }


        //改为材料分类 zhuyujun 20181116
        $mainProductStr = '';
        $mainProduct = $info['main_product'];
        if ($mainProduct) {
            $categoryIdArr = explode(',', $mainProduct);

            //获取分类名称
            $mainProductStr = \App\Eloquent\Ygt\Category::whereIn('id',$categoryIdArr)->get()->pluck('cat_name')->toArray();
            if(!empty($mainProductStr)){
                $mainProductStr = implode(',',$mainProductStr);
            }else{
                $mainProductStr = '';
            }
        }

        $data['main_product'] = $mainProduct;
        $data['main_product_str'] = $mainProductStr;

        return $data;
    }
    public function del()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $id                 = request('id');
        if(!$userInfo || !$id)
        {
            xThrow(ERR_PARAMETER );
        }
        $companyId          = $userInfo->company_id;
        $where              = ['id'=>$id,'company_id'=>$companyId];
        $delResult          = SellerCompany::del($where);
        if(!$delResult)
        {
            xThrow(ERR_UNKNOWN,'删除失败' );
        }
        return ['message'=>'删除成功'];
    }
    public function level()
    {
        $result         = SellerCompany::getLevelListByType();
        return $result;
    }
}